import { SerialPort, DelimiterParser, InterByteTimeoutParser } from "serialport";
import { ipcMain } from "electron";

const serials = {};

export function initSerialIpc(mainWindow) {
  ipcMain.handle("serialList", async () => {
    return await SerialPort.list();
  });
  ipcMain.handle(
    "openSerial",
    (e, path, baudRate, stopBits, dataBits, parity, delimiter = "\r\n") => {
      if (serials[path]) {
        mainWindow.webContents.send(`serial-${path}-err`, "串口已被占用！");
      }
      const serial = new SerialPort(
        {
          path,
          baudRate,
          stopBits,
          dataBits,
          parity
        },
        (err) => {
          if (err) {
            mainWindow.webContents.send(`serial-${path}-err`, err.message);
            return;
          }
          serials[path] = serial;
          if (!delimiter) {
            const parser = serial.pipe(
              new InterByteTimeoutParser({ interval: 200, maxBufferSize: 12 })
            );
            parser.on("data", (d) => {
              mainWindow.webContents.send(`serialListener-${path}`, d);
              serial.flush();
            });
          } else {
            const parser = serial.pipe(new DelimiterParser({ delimiter: delimiter }));
            parser.on("data", (d) => {
              if (d[0] === 2) {
                d = d.slice(1);
              }
              mainWindow.webContents.send(
                `serialListener-${path}`,
                String.fromCharCode.apply(null, d)
              );
              serial.flush();
            });
          }
        }
      );
      return path;
    }
  );

  ipcMain.handle("closeSerial", (e, serialName) => {
    serials[serialName].close();
    serials[serialName] = null;
  });

  ipcMain.handle("serialSend", (e, serialName, data) => {
    const serial = serials[serialName];
    serial.write(data);
  });
}
